// 基于Aioxs的网络请求处理
import axios from "axios";
import store from '@/store';
import router from '@/router';

import { removeToken, removeUserInfo } from "./userInfo";


const axiosInstance = axios.create({
    // 基础路径
    // baseURL: 'https://apipc-xiaotuxian-front.itheima.net/', // 上线请求地址
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net/',
    // 超时时间
    timeout: 5000,
});

//请求拦截器
axiosInstance.interceptors.request.use(
    config => {
        //如果token 不为空，那么在请求头中写上
        if (store.state.user.token) {
            config.headers.Authorization = `Bearer ${store.state.user.token}`;
        }
        return config;
    },
    error => {
        console.log(error);
    }
);

axiosInstance.interceptors.response.use(
    response => { 
        
        console.log(response);
        return response ;
    
    },
    err => {
        //token 失效
        if (err.response.status == 401) {
            //处理token
            removeToken();
            removeUserInfo();

            //处理退出登录
            store.commit('user/loginOut');

            //跳转登录页面
            router.push('/login');
        }
        return Promise.reject(err);
    }
);

export default axiosInstance;